package com.lemon.datasource.config;

import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.lemon.datasource.properties.DataSourceProperties;
import com.lemon.datasource.provider.JdbcDynamicDataSourceProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 李猛
 * @datetime 2024/2/18 1:21
 * @description 类对象
 */
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@EnableConfigurationProperties(DataSourceProperties.class)
public class DynamicDataSourceConfiguration {

    @Bean
    public DynamicDataSourceProvider dynamicDataSourceProvider(DataSourceProperties properties) {
        DefaultDataSourceCreator creator = new DefaultDataSourceCreator();
        // 添加默认主数据源
        DataSourceProperty property = new DataSourceProperty();
        property.setUsername(properties.getUsername());
        property.setPassword(properties.getPassword());
        property.setUrl(properties.getUrl());
        property.setLazy(true);
        creator.createDataSource(property);
        return new JdbcDynamicDataSourceProvider(creator, properties);
    }
}
